package com.mall.user.services;

import com.alibaba.fastjson.JSON;
import com.mall.commons.tool.exception.BizException;
import com.mall.commons.tool.exception.ValidateException;
import com.mall.user.IUserLoginService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.converter.MemberConverter;
import com.mall.user.dal.entitys.Member;
import com.mall.user.dal.persistence.MemberMapper;
import com.mall.user.dto.*;
import com.mall.user.utils.JwtTokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.regex.Pattern;

@Service
@Slf4j
public class UserLoginServiceImpl implements IUserLoginService {

    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private MemberConverter memberConverter;

    @Override
    public UserLoginResponse login(UserLoginRequest request) {
        UserLoginResponse response = new UserLoginResponse();
        try {
            request.requestCheck();
            // 密码加密
            String password = DigestUtils.md5DigestAsHex(request.getPassword().getBytes());
            Example example = new Example(Member.class);
            int flag = 0;
            //激活用户可以使用邮箱登录，或者用户名登录。
            if (Pattern.matches("^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$", request.getUserName())) {
                example.createCriteria().andEqualTo("email", request.getUserName()).andEqualTo("password", password);
                flag = 1;
            } else {
                example.createCriteria().andEqualTo("username", request.getUserName()).andEqualTo("password", password);
            }

            List<Member> members = memberMapper.selectByExample(example);
            // 若members为空，则用户名或邮箱或密码错误
            if (members.size() == 0 && flag == 1) {
                throw new ValidateException(SysRetCodeConstants.EMAILORPASSWORD_ERRROR.getCode(),
                        SysRetCodeConstants.EMAILORPASSWORD_ERRROR.getMessage());
            } else if(members.size() == 0 && flag == 0) {
                throw new ValidateException(SysRetCodeConstants.USERORPASSWORD_ERRROR.getCode(),
                        SysRetCodeConstants.USERORPASSWORD_ERRROR.getMessage());
            }

            response = memberConverter.member2UserRes(members.get(0));
            String token = JwtTokenUtils.builder().msg(members.get(0).getUsername()).build().creatJwtToken();
            response.setToken(token);
            log.info("用户登录成功，登录信息request:{}", JSON.toJSONString(request));
            response.setCode(SysRetCodeConstants.SUCCESS.getCode());
            response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
            //验证用户是否激活,激活用户可以使用邮箱登录，或者用户名登录。
            String isVerified = members.get(0).getIsVerified();
            if ("N".equals(isVerified)){
                throw  new ValidateException(SysRetCodeConstants.USER_ISVERFIED_ERROR.getCode(),
                        SysRetCodeConstants.USER_ISVERFIED_ERROR.getMessage());
            }

        } catch (ValidateException e) {
            response.setCode(e.getErrorCode());
            response.setMsg(e.getMessage());
        } catch (Exception e) {
            response.setCode(SysRetCodeConstants.DB_EXCEPTION.getCode());
            response.setMsg(SysRetCodeConstants.DB_EXCEPTION.getMessage());
        }
        return response;
    }

    @Override
    public CheckAuthResponse validToken(CheckAuthRequest checkAuthRequest) {
        CheckAuthResponse checkAuthResponse = new CheckAuthResponse();

        try {
            checkAuthRequest.requestCheck();

            String msg = JwtTokenUtils.builder().token(checkAuthRequest.getToken()).build().freeJwt();
            Example example = new Example(Member.class);
            example.createCriteria().andEqualTo("username", msg);
            List<Member> members = memberMapper.selectByExample(example);
            if (members.size() == 0)
                throw new BizException(SysRetCodeConstants.TOKEN_VALID_FAILED.getCode(),
                        SysRetCodeConstants.TOKEN_VALID_FAILED.getMessage());

            UserInfoDto userInfoDto = new UserInfoDto();
            userInfoDto.setUid(members.get(0).getId());
            userInfoDto.setUsername(members.get(0).getUsername());
            String jsonString = JSON.toJSONString(userInfoDto);
            checkAuthResponse.setUserinfo(jsonString);
            checkAuthResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
            checkAuthResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        } catch (ValidateException e) {
            checkAuthResponse.setCode(e.getErrorCode());
            checkAuthResponse.setMsg(e.getMessage());
        } catch (BizException e) {
            checkAuthResponse.setCode(e.getErrorCode());
            checkAuthResponse.setMsg(e.getMessage());
        } catch (Exception e) {
            checkAuthResponse.setCode(SysRetCodeConstants.DB_EXCEPTION.getCode());
            checkAuthResponse.setMsg(SysRetCodeConstants.DB_EXCEPTION.getMessage());
        }
        return checkAuthResponse;
    }
}
